package de.servicezombie.lang;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import de.servicezombie.tcmdb.TcmdbException;

public abstract class ExceptionUtils {
	
	private static final Logger log = LoggerFactory.getLogger(ExceptionUtils.class);

	public static IllegalStateException wrapUnexpectedException(Throwable e) {
		return new IllegalStateException("wrapped unexpected exception: " + e.getMessage(), e);
	}
	
	public static RuntimeException wrapException(Throwable cause, ErrorCode errorCode, String message) {
		TcmdbException ex = new TcmdbException(message, cause).attachErrorCode(errorCode);
		return ex;
	}
	
	public static RuntimeException wrapException(Throwable cause, Class<? extends RuntimeException> thrownException) {
		
		String message = cause.getMessage();
		RuntimeException ex;
		
		try {
			ex = thrownException.getConstructor(String.class, Throwable.class).newInstance(message , cause);
		}
		catch (Exception e) {
			logErrorWithStacktrace(log, "unable to build exception instance for " + thrownException.getName(), e);
			return new RuntimeException(message, cause);
		}
		return ex;
	}

	public static void logWarningWithStacktrace(Logger log, final String message, Throwable cause) {
		log.warn(message + "[" + cause.getMessage() + "]");
		if (log.isDebugEnabled()) {
			log.debug("dumpStacktrace: ", cause);
		}
	}
	
	public static void logErrorWithStacktrace(Logger log, final String message, Throwable cause) {
		log.error(message + "[" + cause.getMessage() + "]");
		if (log.isDebugEnabled()) {
			log.debug("dumpStacktrace: ", cause);
		}
	}
	
}
